#!/bin/bash
#指定文件保存路径
echo "请输入本地数据保存路径(默认/app/docker/kodcloud)"
read h
home=${h:-"/app/docker/kodcloud"}
mkdir -p ${home}
#复制目录必须加上-r
cp redis mysql kod nginx ${home}/ -f  -r &>/dev/null
#脚本执行中,脚本也可以复制本身
cp START   ${home}/START &>/dev/null

docker network create kodnet &>/dev/null

#指定kodcloud网站域名
echo -e "输入kodcloud域名,这是在浏览器中的URL地址:"
read new_web
if [ ! -z ${new_web} ] && [ ${new_web} -ne kod.wym.com ]; then
  web=$(ls ${home}/nginx/conf.d)
  sed -i  "s#server_name.*#server_name ${new_web};#" ${home}/nginx/conf.d/${web}
  mv ${home}/nginx/conf.d/${web} ${home}/nginx/conf.d/${new_web} &>/dev/null
  rm ${home}/nginx/conf.d/${web} -f
else
  echo "默认域名为kod.wym.com"
fi



echo "正在启动kodcloud"

#redis
echo "正在安装redis"
docker stop kod-redis &>/dev/null
docker rm kod-redis &>/dev/null
docker rmi wym/redis:kod &>/dev/null
cd ${home}/redis
docker build -t wym/redis:kod . &>/dev/null
docker run -d -it \
--name kod-redis \
--network kodnet  \
-v /app/docker/kodcloud/redis/data:/data \
wym/redis:kod  &>/dev/null
is_redis=$(docker ps|grep wym/redis:kod|wc -l)
if [ ${is_redis} -eq 0 ]; then
  echo "redis启动失败,退出安装"
  exit 1;
fi
echo "redis安装成功"

#mysql
echo "正在安装mysql(第一次需要2-5min)"
docker stop kod-mysql &>/dev/null
docker rm kod-mysql &>/dev/null
docker rmi wym/kod-mysql &>/dev/null
cd ${home}/mysql
docker build -t  wym/mysql:kod  --build-arg MYSQL_R_P=MyStr0ngP@ssw0rd! . &>/dev/null
#--build-arg需要在构建时进行设置
docker run -d -it \
--name kod-mysql \
-v /app/docker/kodcloud/mysql/mysql:/var/lib/mysql  \
-v /app/docker/kodcloud/mysql/logs:/logs \
--network kodnet \
 wym/mysql:kod &>/dev/null
is_mysql=$(docker ps|grep wym/mysql:kod|wc -l)
if [ ${is_mysql} -eq 0 ]; then
  echo "mysql启动失败,退出安装"
  exit 1;
fi
echo "mysql安装成功"

#kod
echo "正在安装kod"
docker stop kod &>/dev/null
docker rm kod &>/dev/null
docker rmi wym/kodcloud:kod  &>/dev/null
cd ${home}/kod
docker build -t wym/kodcloud:kod . &>/dev/null
docker run -d -it --name kod --network kodnet -v /app/docker/kodcloud/kod/html:/var/www/html wym/kodcloud:kod  &>/dev/null
is_kod=$(docker ps|grep wym/kodcloud:kod|wc -l)
if [ ${is_kod} -eq 0 ]; then
  echo "kodcloud启动失败,退出安装"
  exit 1;
fi


#nginx
#nginx必须后于kod安装,否则会出现配置错误
echo "正在安装nginx"
docker stop kod-nginx &>/dev/null
docker rm kod-nginx &>/dev/null
docker rmi wym/nginx:kod &>/dev/null
cd ${home}/nginx
docker build -t  wym/nginx:kod . &>/dev/null
docker run -d -it \
-p 888:80 \
--name kod-nginx \
-v /app/docker/kodcloud/nginx/conf.d:/etc/nginx/conf.d \
-v /app/docker/kodcloud/nginx/html:/usr/share/nginx/html \
--network kodnet \
wym/nginx:kod  &>/dev/null
is_nginx=$(docker ps|grep wym/nginx:kod|wc -l)
if [ ${is_nginx} -eq 0 ]; then
  echo "nginx启动失败,退出安装"
  exit 1;
fi
echo "nginx安装成功"


echo "请访问${new_web}:888"
echo "数据已经存入${home}"
echo "kodcloud已经启动"
